﻿namespace Resonator.Domain.Models
{
	using System;
	using System.Globalization;
	using Castle.ActiveRecord;
	using NHibernate.Search.Attributes;
	using Field = NHibernate.Search.Attributes.FieldAttribute;

	public abstract class LocalizableModel : ResonatorModel
	{
		private CultureInfo _culture = CultureInfo.InvariantCulture;

		public virtual CultureInfo Culture
		{
			get { return _culture; }
			set { _culture = value ?? CultureInfo.InvariantCulture; }
		}

		[Property]
		public virtual int LCID
		{
			get { return _culture.LCID; }
			set
			{
				try
				{
					Culture = CultureInfo.GetCultureInfo(value);
				}
				catch (ArgumentException)
				{
					Culture = null;
				}
			}
		}

		[Field(Index.Tokenized, Store = Store.No)]
		public virtual string LanguageName
		{
			get { return _culture.Name; }
		}

		[Field(Index.Tokenized, Store = Store.No)]
		public virtual string WindowsLanguageName
		{
			get { return _culture.ThreeLetterWindowsLanguageName; }
		}

		[Field(Index.Tokenized, Store = Store.No)]
		public virtual string EnglishName
		{
			get { return _culture.EnglishName; }
		}

		protected override void GetFullText(System.Text.StringBuilder builder)
		{
			base.GetFullText(builder);

			builder.Append(LCID.ToString(CultureInfo.InvariantCulture));
			builder.Append(' ');
			builder.Append(LanguageName);
			builder.Append(' ');
			builder.Append(WindowsLanguageName);
			builder.Append(' ');
			builder.Append(EnglishName);
		}
	}
}
